cmake_minimum_required(VERSION 3.15)  # 推荐使用更高版本
project(ODBExample VERSION 1.0 LANGUAGES CXX)

# 强制使用 Ninja 或 VS2019 生成器以获得更好路径处理
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")  # 关键 MSVC 配置

# 使用短路径格式避免空格问题（8.3命名规则）
set(ODB_ROOT "C:/odb")                   # 对应 C:\Program Files\odb
set(MYSQL_CONNECTOR_ROOT "C:/PROGRA~1/MySQL/Connector C++ 8.0")

# 定义生成器函数（处理 ODB 代码生成）
function(generate_odb_source input_file)
  get_filename_component(base_name ${input_file} NAME_WE)
  set(generated_files
    ${CMAKE_CURRENT_BINARY_DIR}/${base_name}-odb.hxx
    ${CMAKE_CURRENT_BINARY_DIR}/${base_name}-odb.ixx
    ${CMAKE_CURRENT_BINARY_DIR}/${base_name}-odb.cxx
  )

  add_custom_command(
    OUTPUT ${generated_files}
    COMMAND ${ODB_ROOT}/bin/odb.exe
      -d mysql
      --std c++11
      --generate-query
      --generate-schema
      -I${ODB_ROOT}/include  # 关键：显式添加 ODB 头文件路径
      -I${MYSQL_CONNECTOR_ROOT}/include 
      --output-dir ${CMAKE_CURRENT_BINARY_DIR}
      ${CMAKE_CURRENT_SOURCE_DIR}/src/${base_name}.hxx
    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/${base_name}.hxx
    COMMENT "Generating ODB code for ${base_name}.hxx"
    VERBATIM
  )

  target_sources(odb-example PRIVATE ${generated_files})
endfunction()

# 包含目录
include_directories(
  ${MYSQL_CONNECTOR_ROOT}/include
  ${ODB_ROOT}/include
  ${CMAKE_CURRENT_BINARY_DIR}  # 必须包含生成的 ODB 头文件
)

# 创建可执行目标
add_executable(odb-example
  src/main.cpp
)

# 生成 ODB 代码（必须在 add_executable 之后调用）
generate_odb_source(person.hxx)

# 链接配置
target_link_directories(odb-example PRIVATE
  ${ODB_ROOT}/lib
  ${MYSQL_CONNECTOR_ROOT}/lib64/vs14
)

target_link_libraries(odb-example PRIVATE
  libodb
  libodb-mysql
  mysqlcppconn8
)

# Windows DLL 自动复制
if(WIN32)
  add_custom_command(TARGET odb-example POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy
      "${ODB_ROOT}/bin/libodb-2.4.dll"
      $<TARGET_FILE_DIR:odb-example>
    COMMAND ${CMAKE_COMMAND} -E copy
      "${ODB_ROOT}/bin/libodb-mysql-2.4.dll"
      $<TARGET_FILE_DIR:odb-example>
    COMMAND ${CMAKE_COMMAND} -E copy
      "${MYSQL_CONNECTOR_ROOT}/lib64/vs14/mysqlcppconn8-2-vs14.dll"
      $<TARGET_FILE_DIR:odb-example>
    COMMENT "Copying runtime DLLs"
  )
endif()